<!DOCTYPE HTML>
<html>

{% load my_filter %}

<head>
	<title>Add Solution</title>
	{% include 'includes.inc' %}
	<style type="text/css">
		@import "{{STATIC_URL}}css/demo_page.css";
		@import "{{STATIC_URL}}css/demo_table.css";
		.control {
			margin-bottom: 1em;
			text-align: center;
		}
		.control_label {
			margin: 0 70px 0 5px;
		}
		#testcase_pane {
			overflow: hidden;
			margin-bottom: 2em;
		}
		.field_error {
			color: #DD0000;
		}
		#tabs {
			margin-bottom: 2em;
		}
	</style>

	<script src="{{STATIC_URL}}codemirror-compressed.js"></script>
	<link rel="stylesheet" href="{{STATIC_URL}}/codemirror.css">
	<script src="{{STATIC_URL}}js/jquery.dataTables.js"></script>
	<script src="{{STATIC_URL}}jquery.json-2.3.min.js"></script>

	<script>
		$(document).ready(function() {

			var SIGNATURE = {{ signature|tojsonstring }};
			var RETURN_TYPE = '{{ question.return_type|safe }}';
			var QUESTION_ID = {{ question.id }};
			var solutions = {{ solutions|safe }};
			var solutionTable = null;
			var testcaseTable = new TestcaseTable(getDataTableConfig(), 'for_run');
			// pre-load solution
			var preLoadSolId = {{ loadSolution|safe }};
			var editMode = {{ editMode|safe }};

			// tabs setup
			$( "#tabs" ).tabs();

			// codemirror setup
			var solutionManager = {
				"my_sol":{
					"div": "my_sol",
					"isPresent": false,
					"sol": null,
					"codemirror": null
				},
				"ref_sol_1":{
					"div": "ref_sol_1",
					"isPresent": false,
					"sol": null,
					"codemirror": null
				},
				"ref_sol_2":{
					"div": "ref_sol_2",
					"isPresent": false,
					"sol": null,
					"codemirror": null
				}
			};

			var currentTab = solutionManager.my_sol;
			if (preLoadSolId !== false) {
				if (editMode == false) {
					currentTab = solutionManager.ref_sol_1;
				}
				currentTab.isPresent = true;
				currentTab.sol = solutions['sol_' + preLoadSolId];
			}

			initializeTabs(solutionManager);
			initializeSolutionTable(solutions);

			$('#tabs ul li a').click(function(){
				var tabId = $(this).attr('href');
				tabId = tabId.substring(1);
				currentTab = solutionManager[tabId];
			});

			// button listeners
			$('#add_solution_form, #solution_div').dialog({
				autoOpen: false,
				width: 500,
				show: "blind",
            hide: "blind"
			})/*
			.parent()
			.draggable({cancel:'input,select',handle:''})*/;

			$(".ui-dialog-titlebar").hide();

			// adding new solution
			$('#open_add_sol_dialog').click(function(){
				$('#add_solution_form').dialog("open");
			});
			$('#close_add_dialog').click(function(){
				$('#add_solution_form').dialog("close");
			});
			$('#add_sol').click(function(){
				validateAndCreateSolution();
			});

			// load existing solution
			$('.open_load').click(function(){
				$('#solution_div').dialog("open");
			});
			$('#close_load_dialog').click(function(){
				$('#solution_div').dialog("close");
			});

			// close solution
			$('.close').click(function(){
				var config = currentTab;
				if(config.isPresent){
					removeCodeMirror(config);
				}
			});

			// save (my) solution
			$('#save_sol').click(function(){
				var config = solutionManager.my_sol;
				if(!config.isPresent){
					return;
				}
				config.sol.program = config.codemirror.getValue();
				$.ajax({
						contentType: "application/json; charset=utf-8",
						data: $.toJSON(config.sol),
						dataType: 'json',
						type: 'POST',
						url: '/t/UpdateSolution',
						beforeSend: function() {
							$('#sol_loading').fadeIn('slow');
						},
						success: function(data) {
							if(data.result == 'OK'){
								updateCodeMirror(solutionManager.my_sol, data.sol);
								var s_id = 'sol_' + data.sol.sol_id;
								solutions[s_id] = data.sol;
							} else {
							}
							$('#sol_loading').fadeOut('slow');
						},
						error: function(xhr, textStatus, errorThrown) {
							alert(textStatus);
							$('#sol_loading').fadeOut('slow');
						}
					});
			});

			// run solution
			$('.run').click(function(){
				var run_req = {"run_req":{}};
				var sol_ids = [];
				for(tab in solutionManager){
					sol = solutionManager[tab];
					if(sol.isPresent){
						sol_ids.push(sol.sol.sol_id);
					}
				}
				if(sol_ids.length < 1){
					alert("There's no solution to run.");
					return;
				}
				if (sol_ids.length > 2){
					alert("At most two solutions can run.");
					return;
				}

				run_req["run_req"]["sol_ids"] = sol_ids;
				testcaseTable.hideRunResult();

				//TODO: add testcase ID selection
				$.ajax({
						contentType: "application/json; charset=utf-8",
						data: $.toJSON(run_req),
						dataType: 'json',
						type: 'POST',
						url: '/t/RunSolution',
						beforeSend: function() {
							$('#sol_loading').fadeIn('slow');
						},
						success: handleSuccessRun,
						error: function(xhr, textStatus, errorThrown) {
							alert(textStatus);
							$('#sol_loading').fadeOut('slow');
						}
					});
			});

			function handleSuccessRun(data) {
				if(data.status == 'OK'){
					for(var s_id in data.result){
						var result  = data.result[s_id];
						s_id = s_id.substring(4);// strip sol_
						if(result.status != 'OK') {
							alert('Solution ' + s_id + ' failed to run.');
							continue;
						}
						for(var sm in solutionManager){
							var sol = solutionManager[sm]
							if(sol.isPresent &&
								sol.sol.sol_id == s_id){
								testcaseTable.updateResult(sm,result.result);
							}
						}
					}
					// scroll to the result
					$('html,body').animate({scrollTop: $("#testcase_pane").offset().top},'slow');
				} else {
					alert(data.message);
				}
				$('#sol_loading').fadeOut('slow');
			}


			function validateAndCreateSolution() {
				var name = $('#add_sol_name').val();
				if(!name || !name.length || name.lenth < 3){
					$('#add_sol_name').addClass('field_error');
					return;
				}
				var req = {'name': name,
					'lang': $('#add_sol_lang').val(),
					'question_id': QUESTION_ID
				};

				$.ajax({
						contentType: "application/json; charset=utf-8",
						data: $.toJSON(req),
						dataType: 'json',
						type: 'POST',
						url: '/t/UpdateSolution',
						beforeSend: function() {
							$('#add_sol_loading').fadeIn('slow');
						},
						success: handleAddSolSuccess,
						error: function(xhr, textStatus, errorThrown) {
							alert(textStatus);
							$('#add_sol_loading').fadeOut('slow');
						}
					});
			} //validateAndCreateSolution

			// handle add solution stub response from server
			function handleAddSolSuccess(data){
				if(data.result == 'OK'){
					updateCodeMirror(solutionManager.my_sol, data.sol);
					var s_id = 'sol_' + data.sol.sol_id;
					solutions[s_id] = data.sol;
					var rowIdx = solutionTable.fnAddData(getSolutionRow(data.sol))[0];
					$(solutionTable.fnGetNodes()[rowIdx]).click(function () {
						//TODO: make this a function and remove duplicate
						var sData = solutionTable.fnGetData( this );
						var s_id = 'sol_' + sData[0];
						loadSolution(solutions[s_id]);
						$('#solution_div').dialog("close");
					});

					$('#add_sol_loading').fadeOut('slow');
					$('#add_solution_form').dialog("close");
				} else {
					alert(data.message);
					$('#add_sol_loading').fadeOut('slow');
				}
			}

			function updateCodeMirror(config, sol){
				if(config.isPresent){
					removeCodeMirror(config);
				}
				var readOnly = (config.div != 'my_sol');
				config.isPresent = true;
				config.sol = sol;

				config.codemirror = CodeMirror(
						document.getElementById(config.div),
						getCodeMirrorConfig(sol, readOnly));
			}

			function removeCodeMirror(config){
				var parent = config.codemirror.getWrapperElement();
				$(parent).remove();
				config.isPresent = false;
				config.sol = null;
			}

			function getDataTableConfig(){
				return {
					"bPaginate": false,
					"bLengthChange": false,
					"bFilter": false,
					"bSort": false,
					"bInfo": false,
					"bAutoWidth": false,
					"aaData": {{ aaData|safe }},
					"aoColumns": {{ aoColumns|safe }}
				};
			}// function getDataTableConfig

			function initializeTabs(sm) {
				for(var tab in sm){
					tab = sm[tab];
					if(!tab.isPresent){
						continue;
					}

					// for some reason tabs needs to be activated before rendering
					// CodeMirror
					$('#tabs').tabs('select', '#' + tab.div); 
					tab.codemirror = CodeMirror(document.getElementById(tab.div),
						getCodeMirrorConfig(tab.sol, !editMode));
				}// for
			}// function initializeTabs

			function getCodeMirrorConfig(sol, readOnly){
				var config = {
					autoClearEmptyLines: true,
					indentUnit: 3,
					indentWithTabs: true,
					lineNumbers: true,
					matchBrackets: true,
					readOnly: readOnly,
					tabSize: 3,
					value: sol.program
				};

				if(sol.lang == 'python2'){
					config.mode = {name: "python",
               	version: 2,
               	singleLineStringErrors: false};
				}

				if(sol.lang == 'java6'){
					config.mode = 'text/x-java'
				}

				return config;
			}// getCodeMirrorConfig(sol)

			function initializeSolutionTable(solutions){

				var aoColumns = [
					{ "sTitle": "ID" },
					{ "sTitle": "Name" },
					{ "sTitle": "Lang" },
					/*{ "sTitle": "Author" },*/
					{ "sTitle": "Last Update" }
				];
				var config = {
					"bPaginate": true,
					"bLengthChange": false,
					"bFilter": true,
					"bSort": true,
					"bInfo": false,
					"bAutoWidth": false,
					"aaData": [],
					"aoColumns": aoColumns 
				};

				for(var s_id in solutions){
					config.aaData.push(
						getSolutionRow(solutions[s_id]));
				}	

				solutionTable = $('#solution_table').dataTable(config);
				solutionTable.fnSetColumnVis(0, false);
				solutionTable.$('tr').click( function () {
					var sData = solutionTable.fnGetData( this );
					var s_id = 'sol_' + sData[0];
					loadSolution(solutions[s_id]);
					$('#solution_div').dialog("close");
				} );

			}// function initializeSolutionTable(solutions)

			function getSolutionRow(sol){
				return [
					sol.sol_id,
					sol.name,
					sol.lang,
					tm(sol.last_update)
				];
			}// function getSolutionRow

			function loadSolution(sol){
				updateCodeMirror(currentTab, sol);
			}

		});
	</script>
</head>

<body>
	<div id="main">

	{% include 'header.inc' %}

    <div id="site_content">
		{% include 'sidebar.inc' %}

      <div id="content">

<h1>My Solution</h1>

<div style="overflow:hidden;">
<div id="tabs">
	<ul>
		<li><a href="#my_sol">My Solution</a></li>
		<li><a href="#ref_sol_1">Reference Solution 1</a></li>
		<li><a href="#ref_sol_2">Reference Solution 2</a></li>
	</ul>
	<div id="my_sol">
		<div class="control">
			<button type="button" class="fancy_button" id="open_add_sol_dialog">New</button>
			<button type="button" class="fancy_button open_load" id="open_load_my_dialog">Load</button>
			<button type="button" class="fancy_button" id="save_sol">Save</button>
			<button type="button" class="fancy_button close">Close</button>
			<button type="button" class="fancy_button run">Run</button>
		</div>
	</div>
	<div id="ref_sol_1">
		<div class="control">
			<button type="button" class="fancy_button open_load">Load</button>
			<button type="button" class="fancy_button close">Close</button>
			<button type="button" class="fancy_button run">Run</button>
		</div>
	</div>
	<div id="ref_sol_2">
		<div class="control">
			<button type="button" class="fancy_button open_load">Load</button>
			<button type="button" class="fancy_button close">Close</button>
			<button type="button" class="fancy_button run">Run</button>
		</div>
	</div>
	<div id="solution_div">
		<table class="display" cellpadding="0" cellspacing="0" border="0" id="solution_table"></table>
		<input type="button" class="fancy_button" name="close_load_dialog" id="close_load_dialog" value="Close">
	</div>
	<div class="loading" id="sol_loading"></div>
</div><!-- close tabs div -->
</div>

<div id="add_solution_form" title="Add New Solution" class="form_settings">
	<h3>Add New Solution!</h3>
	<form>
		<p>
			<span>Pick your weapon</span>
			<select id="add_sol_lang">
				<option value="python2">Python 2</option>
				<option value="java6">Java 6</option>
			</select>
		</p>
		<p>
			<span>Name your solution</span>
			<input type='text' id='add_sol_name' name='add_sol_name' maxlength='32'>
		</p>
		<p>
			<input type="button" class="fancy_button" name="add_sol" id="add_sol" value="Add">
			<input type="button" class="fancy_button" name="close_add_dialog" id="close_add_dialog" value="Close">
		</p>
	</form>
	<div class="loading" id="add_sol_loading"></div>
</div>

{% include 'problem-description.inc' %}

<h1>Testcases</h1>
<div id="testcase_pane">
	<div id="testcase_table_pane">
		<table class="display" cellpadding="0" cellspacing="0" border="0" id="testcase_table"></table>
	</div>	
</div>


      </div><!-- close content div -->
    </div><!-- close site_content div -->

	{% include 'footer.inc' %}
  </div>

</body>
</html>
